package parse;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import config.Configuration;
import io.Resources;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.InputStream;
import java.util.List;
import java.util.Properties;

/**
 * @CreatedBy richInfo AI
 * @ClassName ConfigMapperParse
 * @Date 2021/8/16 2:21 下午
 * @Author xin.yang
 * @Description TODO
 */
public class ConfigMapperParse
{

    public Configuration parse(InputStream in) throws Exception
    {
        SAXReader saxReader = new SAXReader();
        Document document = saxReader.read(in);
        Element rootElement = document.getRootElement();
        List<Element> list = rootElement.selectNodes("//property");
        Properties properties = new Properties();
        for (Element element : list)
        {
            properties.setProperty(element.attributeValue("name"), element.attributeValue("value"));
        }
        ComboPooledDataSource dataSource = new ComboPooledDataSource();
        dataSource.setDriverClass(properties.getProperty("driverClass"));
        dataSource.setJdbcUrl(properties.getProperty("url"));
        dataSource.setUser(properties.getProperty("user"));
        dataSource.setPassword(properties.getProperty("password"));
        Configuration configuration = new Configuration();
        configuration.setDatasource(dataSource);
        List<Element> mappers = rootElement.selectNodes("//mapper");
        for (Element mapper : mappers)
        {
            String path = mapper.attributeValue("resource");
            MapperParse mapperParse = new MapperParse(configuration);
            InputStream resources = Resources.resources(path);
            mapperParse.parse(resources);
        }
        return configuration;
    }
}
